package com.haiyou.mini.programs.service.impl;


import com.haiyou.common.exception.BusinessException;
import com.haiyou.common.util.RequestUtils;
import com.haiyou.mini.programs.config.WxMiniConfig;
import com.haiyou.mini.programs.service.WxMiniPayNotifyCallbackService;
import com.haiyou.mini.programs.service.WxMiniPayNotifyService;
import com.haiyou.mini.programs.wxpay.WxPayXmlUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 小程序支付回调服务
 */
@Slf4j
@RequiredArgsConstructor
public class WxMiniPayNotifyServiceImpl implements WxMiniPayNotifyService {

    private final WxMiniConfig wxMiniConfig;

    @Override
    public void wxNotify(WxMiniPayNotifyCallbackService notifyCallbackService) {
        HttpServletRequest request = RequestUtils.getRequest();
        HttpServletResponse response = RequestUtils.getResponse();

        Map<String, String> notifyMap;
        try {
            notifyMap = WxPayXmlUtil.checkNotify(wxMiniConfig, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("--->回调异常,message={}，e={}", e.getMessage(), e);
            throw new BusinessException("支付回调异常");
        }
        //回调处理
        if (notifyCallbackService != null) {
            notifyCallbackService.wxNotifyCallback(notifyMap);
        }
        log.info("------>处理成功");
        WxPayXmlUtil.sendWxNoticeMessage("SUCCESS", "OK", response);
    }

}
